import Vue from 'vue';
import axios from 'axios'
import router from '@/router';

import {
    Toast,
    Dialog
} from 'vant';
import moment from 'moment'
import db from './localstorage'
import {
    Base64
} from 'js-base64';
moment.locale('zh-cn')

Vue.use(Toast);

const serialize = data => {
    let list = [];
    Object.keys(data).forEach(ele => {
        list.push(`${ele}=${data[ele]}`)
    })
    return list.join('&');
};

// 统一配置
let FEBS_REQUEST = axios.create({
    baseURL: 'http://api.tiaopiwu.com/',
    // baseURL: 'http://api.tiaopiwu.com/',
    responseType: 'json',
    validateStatus(status) {
        // 200 外的状态码都认定为失败
        return status === 200
    }
})

// 拦截请求
FEBS_REQUEST.interceptors.request.use((config) => {
    const meta = (config.meta || {});
    // let expireTime = store.state.account.expireTime
    // let now = moment().format('YYYYMMDDHHmmss')

    let date = new Date()
    let now = date.getTime()
    let expireTime = db.get('expireTime')
    // 让token早10秒种过期，提升“请重新登录”弹窗体验
    if (expireTime && (now - expireTime >= -10 * 1000)) {
        Toast({
            message: '登录已过期',
            onClose: () => {
                return new Promise(() => {
                    db.clear()
                    location.reload()
                })
            }
        });
    }
    let token = window.localStorage.getItem('token')
    // if (!token) {
    //     router.push({
    //         path: '/login'
    //     })
    // }
    config.headers['Token'] = token

    // config.headers.Authentication = `Basic ${Base64.encode(`${website.clientId}:${website.clientSecret}`)}`;
    // 有 token就带上
    // if (!config.headers['Blade-Auth']) {
    //     config.headers['Blade-Auth'] = `bearer ${window.localStorage.getItem('Authorization') || ''}`
    // }
    //headers中配置serialize为true开启序列化
    // if (config.method === 'post' && meta.isSerialize === true) {
    //     config.data = serialize(config.data);
    // }

    return config
}, (error) => {
    return Promise.reject(error)
})

// 拦截响应
FEBS_REQUEST.interceptors.response.use((config) => {
    let {
        data
    } = config
    if (data.url == -3001 || data.url == -3002 || data.url == -3003) {
        Dialog.alert({
            message: data.info,
        }).then(() => {
            router.push({
                path: '/login'
            })
        });
    }
    return config
}, (error) => {
    console.log(error, 'error');

    if (error.response) {
        let errorMessage = error.response.data === null ? '系统内部异常，请联系网站管理员' : error.response.data.message
        switch (error.response.status) {
            case 404:
                Toast.fail('很抱歉，资源未找到');
                break
            case 403:
            case 401:
                Toast.fail('很抱歉，您无法访问该资源，可能是因为没有相应权限或者登录已失效');
                break
            case 500:
                Toast.fail(errorMessage);
                break
            default:
                Toast.fail(errorMessage);
                break
        }
    }
    return Promise.reject(error)
})

const request = {
    // 可实现form-data数据上传
    post(url, params, config) {
        let headers = {
            'Content-Type': 'application/x-www-form-urlencoded',
            ...config
        }
        let postData = {
            headers: headers
        }

        if (!config) {
            postData = {
                ...{
                    transformRequest: [(params) => {
                        let result = ''
                        Object.keys(params).forEach((key) => {
                            if (!Object.is(params[key], undefined) && !Object.is(params[key], null)) {
                                result += encodeURIComponent(key) + '=' + encodeURIComponent(params[key]) + '&'
                            }
                        })
                        return result
                    }],
                }
            }
        }
        return FEBS_REQUEST.post(url, params, postData)
    },
    post1(url, data) {
        return FEBS_REQUEST.post(url, params, {
            transformRequest: [(params) => {
                if (data.headers) return params
                let result = ''
                Object.keys(params).forEach((key) => {
                    if (!Object.is(params[key], undefined) && !Object.is(params[key], null)) {
                        result += encodeURIComponent(key) + '=' + encodeURIComponent(params[key]) + '&'
                    }
                })
                return result
            }],
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            }
        })
    },
    put(url, params) {
        return FEBS_REQUEST.put(url, params, {
            transformRequest: [(params) => {
                let result = ''
                Object.keys(params).forEach((key) => {
                    if (!Object.is(params[key], undefined) && !Object.is(params[key], null)) {
                        result += encodeURIComponent(key) + '=' + encodeURIComponent(params[key]) + '&'
                    }
                })
                return result
            }],
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        })
    },
    get(url, params = {}) {
        let _params
        if (Object.is(params, undefined)) {
            _params = ''
        } else {
            _params = '?'
            for (let key in params) {
                if (params.hasOwnProperty(key) && params[key] !== null) {
                    _params += `${key}=${params[key]}&`
                }
            }
        }
        return FEBS_REQUEST.get(`${url}${_params}`)
    },
    delete(url, params) {
        let _params
        if (Object.is(params, undefined)) {
            _params = ''
        } else {
            _params = '?'
            for (let key in params) {
                if (params.hasOwnProperty(key) && params[key] !== null) {
                    _params += `${key}=${params[key]}&`
                }
            }
        }
        return FEBS_REQUEST.delete(`${url}${_params}`)
    },
    export (url, params = {}) {
        Toast.loading({
            mask: true,
            message: '导出数据中...'
        });
        return FEBS_REQUEST.post(url, params, {
            transformRequest: [(params) => {
                let result = ''
                Object.keys(params).forEach((key) => {
                    if (!Object.is(params[key], undefined) && !Object.is(params[key], null)) {
                        result += encodeURIComponent(key) + '=' + encodeURIComponent(params[key]) + '&'
                    }
                })
                return result
            }],
            responseType: 'blob'
        }).then((r) => {
            const content = r.data
            const blob = new Blob([content])
            const fileName = `${new Date().getTime()}_导出结果.xlsx`
            if ('download' in document.createElement('a')) {
                const elink = document.createElement('a')
                elink.download = fileName
                elink.style.display = 'none'
                elink.href = URL.createObjectURL(blob)
                document.body.appendChild(elink)
                elink.click()
                URL.revokeObjectURL(elink.href)
                document.body.removeChild(elink)
            } else {
                navigator.msSaveBlob(blob, fileName)
            }
        }).catch(() => {
            Toast.fail('导出失败')
        })
    },
    download(url, params, filename) {
        Toast.loading({
            mask: true,
            message: '文件传输中...'
        });
        return FEBS_REQUEST.post(url, params, {
            transformRequest: [(params) => {
                let result = ''
                Object.keys(params).forEach((key) => {
                    if (!Object.is(params[key], undefined) && !Object.is(params[key], null)) {
                        result += encodeURIComponent(key) + '=' + encodeURIComponent(params[key]) + '&'
                    }
                })
                return result
            }],
            responseType: 'blob'
        }).then((r) => {
            const content = r.data
            const blob = new Blob([content])
            if ('download' in document.createElement('a')) {
                const elink = document.createElement('a')
                elink.download = filename
                elink.style.display = 'none'
                elink.href = URL.createObjectURL(blob)
                document.body.appendChild(elink)
                elink.click()
                URL.revokeObjectURL(elink.href)
                document.body.removeChild(elink)
            } else {
                navigator.msSaveBlob(blob, filename)
            }
        }).catch(() => {
            Toast.fail('下载失败')
        })
    },
    upload(url, params) {
        return FEBS_REQUEST.post(url, params, {
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        })
    }
}

export default request